<template>
  <div :class="$style.wrap">
    <Button type="primary" @click="showHandle">人员变更</Button>
    <el-dialog :visible.sync="visible" title="人员变更" width="70vw" :close-on-click-modal="false" @open="handleOpen" @close="resetForm">
      <FormContainer :column="2">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item label="业务组" prop="groupId">
            <el-select v-model="formData.groupId" :disabled="!!formData.handlerPostCode" placeholder="请选择业务组" clearable filterable @change="handleChange">
              <el-option v-for="b in businessList" :key="b.groupNo" :value="b.id" :label="b.groupName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="handlerPostCode" label="岗位">
            <SelectForDict :disabled="!!formData.groupId" :code.sync="formData.handlerPostCode" :name.sync="formData.handlerPostName" dict-type-code="DEPT_POST_CODE" placeholder="请选择岗位" clearable filterable @on-change="handlePostChange"></SelectForDict>
          </el-form-item>
          <el-form-item label="坐席" prop="handler">
            <el-select
              v-if="formData.groupId"
              v-model="formData.handler"
              :disabled="!formData.groupId"
              :class="$style.handler"
              placeholder="请选择坐席"
              remote
              :remote-method="getBusinessMembers"
              clearable
              filterable
              @change="getStaffName"
            >
              <el-option v-for="h in handlerList" :key="h.accountNo" :value="h.accountNo" :label="`${h.staffName}(${h.accountNo})`"></el-option>
            </el-select>
            <SearchSelectPicker
              v-if="formData.handlerPostCode"
              url="/call-center/api/v1/workOrderEcosReceiver/queryPostHandler/page"
              placeholder="请选择"
              lable-name="receiverName"
              value-name="receiver"
              :must-pid="true"
              :parent-id="formData.handlerPostCode"
              :disabled="!formData.handlerPostCode"
              :params="{query:{postCode:formData.handlerPostCode},type:0}"
              :value.sync="formData.handler"
              :lable.sync="formData.handlerName"
              style="width: calc(100% - 60px) !important"
              @selectChange="handleEcosReceiver"
            ></SearchSelectPicker>
            <Button type="primary" size="mini" @click="handleClickAdd">增加</Button>
          </el-form-item>
          <el-form-item label-width="0" :span="24">
            <table-box ref="tableBox" :table-config="tableConfig" :table-height="300" :data="tableData" no-request></table-box>
          </el-form-item>
          <el-form-item :span="24">
            <div style="text-align: right;">
              <Button type="primary" @click="visible=false">取消</Button>
              <Button type="primary" @click="confirmHandle">确定</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
    </el-dialog>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import SelectForDict from '@/components/SelectForDict'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { getBusinessAll, getBusinessMembers } from '@/api/business'
import { filtersRaw, pageRequsetBody, deepCopy } from '@/utils'
import { putWorkOrderHandler, getHandlerList } from '@/api/workOrder'
export default {
  name: 'StaffChange',
  components: {
    FormContainer,
    SelectForDict,
    SearchSelectPicker
  },
  props: {
    selectedArry: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      visible: false,
      formData: {
        groupId: '',
        handler: '', //	处理人账号
        handlerGroupName: '', //	业务组名称
        handlerGroupNo: '', //	业务组编码
        handlerName: '', //	处理人姓名
        handlerPhone: '', //	处理人电话
        handlerPostCode: '', //	岗位编码
        handlerPostName: '', //	岗位名称
        qupOrganization: '', //	QUP组织
        qupOrganizationName: '' //	QUP组织名称
      },
      formRules: {
        // groupId: [{ required: true, message: '请选择业务组', trigger: 'change' }],
        // handlerPostCode: [{ required: true, message: '请选择岗位', trigger: 'change' }],
        handler: [{ required: true, message: '请选择坐席', trigger: 'change' }]
      },
      // 只能选择以下业务组
      groupNoList: ['35', '34', '33', '32', '26', '20', '22', '23', '24'],
      businessList: [],
      // 坐席
      handlerList: [],
      tableConfig: {
        interfacePath: '',
        setting: [
          {
            label: '用户名',
            prop: 'handler'
          },
          {
            label: '业务组',
            prop: 'handlerGroupName'
          },
          {
            label: '岗位',
            prop: 'handlerPostName'
          },
          {
            label: '用户姓名',
            prop: 'handlerName'
          },
          {
            label: '操作',
            prop: 'operator',
            render: (h, row) => {
              return h('span', {
                style: {
                  color: 'red',
                  cursor: 'pointer'
                },
                on: {
                  click: e => this.handleRemove(row, e)
                }
              }, '删除')
            }
          }
        ]
      },
      tableData: [],
      handlerListData: []
    }
  },
  created() {
    this.getBusinessAll()
  },
  methods: {
    // 弹窗
    showHandle() {
      if (this.selectedArry.length === 0) {
        this.$message.info('请选择要操作的数据!')
        this.visible = false
      } else if (this.selectedArry.length > 1) {
        this.$message.info('该操作只能单选!')
        this.visible = false
      } else {
        this.visible = true
      }
    },
    // 获取所有业务组
    getBusinessAll() {
      getBusinessAll().then(res => {
        this.businessList = res.data.filter(e => {
          return this.groupNoList.includes(e.groupNo)
        })
      })
    },
    // 获取坐席
    getBusinessMembers(v) {
      if (!this.formData.groupId) {
        this.handlerList = []
        this.resetForm()
        return
      }
      const data = {
        pageFlag: true,
        filtersRaw: []
      }
      if (/^[a-zA-Z]+$/.test(v)) {
        data.filtersRaw.push(filtersRaw('accountNo', v, 'like'))
      } else {
        data.filtersRaw.push(filtersRaw('staffName', v, 'like'))
      }
      getBusinessMembers(pageRequsetBody(data), this.formData.groupId).then(res => {
        this.handlerList = res.data.records
      })
    },
    handleChange(id) {
      this.$set(this.formData, 'handler', '')
      this.$set(this.formData, 'handlerName', '')
      this.$set(this.formData, 'handlerPhone', '')
      this.$set(this.formData, 'qupOrganization', '')
      this.$set(this.formData, 'qupOrganizationName', '')
      this.$set(this.formData, 'handlerPostCode', '')
      this.$set(this.formData, 'handlerPostName', '')

      if (!id) {
        this.$set(this.formData, 'handlerGroupNo', '')
        this.$set(this.formData, 'handlerGroupName', '')
      }
      for (const item of this.businessList) {
        if (item.id === id) {
          this.$set(this.formData, 'handlerGroupName', item.groupName)
          this.$set(this.formData, 'handlerGroupNo', item.groupNo)
          break
        }
      }
      this.getBusinessMembers('')
    },
    handlePostChange() {
      this.$set(this.formData, 'groupId', '')
      this.$set(this.formData, 'handlerGroupName', '')
      this.$set(this.formData, 'handlerGroupNo', '')
      this.$set(this.formData, 'handler', '')
      this.$set(this.formData, 'handlerName', '')
      this.$set(this.formData, 'handlerPhone', '')
      this.$set(this.formData, 'qupOrganization', '')
      this.$set(this.formData, 'qupOrganizationName', '')
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.tableData = []
    },
    // 获取坐席姓名
    getStaffName(v) {
      if (!v) {
        this.$set(this.formData, 'handler', '')
        this.$set(this.formData, 'handlerName', '')
        this.$set(this.formData, 'handlerPhone', '')
        this.$set(this.formData, 'qupOrganization', '')
        this.$set(this.formData, 'qupOrganizationName', '')
        return
      }
      for (const item of this.handlerList) {
        if (item.accountNo === v) {
          this.$set(this.formData, 'handlerName', item.staffName)
          this.$set(this.formData, 'handlerPhone', '')
          this.$set(this.formData, 'qupOrganization', '')
          this.$set(this.formData, 'qupOrganizationName', item.organization)
        }
      }
    },
    handleEcosReceiver(v) {
      if (!v) {
        this.$set(this.formData, 'handler', '')
        this.$set(this.formData, 'handlerName', '')
        this.$set(this.formData, 'handlerPhone', '')
        this.$set(this.formData, 'qupOrganization', '')
        this.$set(this.formData, 'qupOrganizationName', '')
        return
      }
      this.$set(this.formData, 'handlerPhone', v.receiverPhone)
      this.$set(this.formData, 'qupOrganization', '')
      this.$set(this.formData, 'qupOrganizationName', '')
    },
    // 确认
    confirmHandle() {
      if (this.tableData.length === 0) {
        this.$message.warning('请添加处理人!')
        return
      }
      const data = deepCopy(this.tableData)
      return putWorkOrderHandler(this.selectedArry[0].id, data).then(res => {
        this.$message.success('人员变更成功！')
        this.$emit('on-change-success')
        this.visible = false
      })
    },
    handleClickAdd() {
      return this.$refs.form.validate().then(() => {
        const fn = item => `${item.handler}-${item.handlerPostCode}-${item.groupNo}`
        const uid = fn(this.formData)
        if (this.tableData.some(e => fn(e) === uid)) {
          this.$message.warning('该组合已添加!')
          return
        }
        const d = this.selectedArry[0]
        this.formData.workOrderCode = d.workOrderCode //	工单编码
        this.formData.workOrderId = d.id //	工单ID
        this.tableData.push({ ...this.formData })
        Object.keys(this.formData).forEach(k => {
          this.$set(this.formData, k, '')
        })
      })
    },
    handleRemove(row, e) {
      e.stopPropagation()
      this.tableData.splice(row.keyIndex, 1)
    },
    handleOpen() {
      getHandlerList(this.selectedArry[0].id).then(res => {
        this.tableData = res
      })
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
    text-align: left;
    display: inline-block;
    margin-right: 5px;
    .handler{
      width: calc(100% - 60px) !important;
    }
}
</style>
